import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';

@Injectable()
export class CatsService {
  private i = 0;
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push({
      ...cat,
      id: ++this.i,
    });
  }

  findAll(): Cat[] {
    return this.cats;
  }

  findOne(id: string): Cat {
    const i = Number(id);
    let l = this.cats.length;
    while (l-- > 0) {
      const cat = this.cats[l];
      if (cat.id === i) {
        return cat;
      }
    }
  }

  update(id: string, newcat: Cat) {
    const i = Number(id);
    let l = this.cats.length;
    while (l-- > 0) {
      const cat = this.cats[l];
      if (cat.id === i) {
        this.cats[l] = {
          ...newcat,
          id: i,
        };
        return 0;
      }
    }
    return 1;
  }

  remove(id: string) {
    const i = Number(id);
    let l = this.cats.length;
    while (l-- > 0) {
      const cat = this.cats[l];
      if (cat.id === i) {
        this.cats.splice(l, 1);
        return 0;
      }
    }
    return 1;
  }
}
